package com.fyzk.activity.lottery.togetherbuy;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AbsListView.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.lottery.shuzicai.InfoDetailActivity;
import com.fyzk.activity.user.NetProgressView;
import com.fyzk.adapter.togetherbuy.TogetherbuyListAdapter;
import com.fyzk.bean.togetherbuy.TogetherHallItem;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.dialog.TogetherFilterPop;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.HelpUrlConstants;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.view.TopTitleView;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.layoutmanagers.ScrollSmoothLineaerLayoutManager;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * 合买大厅
 */
@ContentView(R.layout.ac_togetherbuy_hall)
public class TogetherBuyHallActivity extends BaseActivity implements
        onTopTitleClickListener, TogetherbuyListAdapter
        .OnItemClickListener, TogetherFilterPop.OnFilterOKListener {
    @ViewInject(R.id.hm_topTitle)
    private TopTitleView topView;

    @ViewInject(R.id.hm_rdg_filter)
    private RadioGroup hm_rdg_filter;
    @ViewInject(R.id.hm_filter_amount)
    private RadioButton hm_filter_amount;
    @ViewInject(R.id.hm_filter_progress)
    private RadioButton hm_filter_progress;
    @ViewInject(R.id.recordProgressView)
    NetProgressView netProgressView;

    @ViewInject(R.id.together_listview)
    private UltimateRecyclerView togetherbuy_list;

    private String lotteryId = "0";


    public static final int STATE_ALL = 0;//买状态 0全部 1未满员 2满员
    public static final int STATE_HASFILL = 2;//买状态 0全部 1未满员 2满员
    public static final int STATE_NOFILL = 1;//买状态 0全部 1未满员 2满员

    public static final int SAFEAMOUNT_ALL = 0;//int	是否保底 1保底 2不保底 0全部
    public static final int SAFEAMOUNT_HAS = 1;//int	是否保底 1保底 2不保底 0全部
    public static final int SAFEAMOUNT_NO = 2;//int	是否保底 1保底 2不保底 0全部

    private final int SORTTYPE_PROGRESS = 1;// 按进度1进度 2战绩 3彩金
    private final int SORTTYPE_MONEY = 3;// 按彩金

    private int isSafeAmount = SAFEAMOUNT_ALL;
    private int state = STATE_NOFILL;
    private int sortType = SORTTYPE_PROGRESS;

    private int pageIndex = 1;
    private int maxResult = 6;
    private ArrayList<TogetherHallItem> togetherbuyInfos = new ArrayList<>();
    private boolean isLoadMore = false;
    private TogetherbuyListAdapter togetherbuyListAdapter;


    private TogetherFilterPop top_popup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        pageIndex = 1;
        net();
    }


    protected void net() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("state", state);
            request_json.put("lotteryType", lotteryId);
            request_json.put("isSafeAmount", isSafeAmount);
            request_json.put("sortType", sortType);
            request_json.put("pageIndex", pageIndex);
            request_json.put("maxResult", maxResult);
            httpPostJson(CommandUtil.FINDCASELOTS, Commands.FINDCASELOTS, request_json, false);
        } catch (JSONException e) {

        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        netProgressView.dismiss();
        switch (requestCode) {
            case CommandUtil.FINDCASELOTS:
                if (resultBean.getErrorcode().equals("0")) {
                    try {
                        JSONObject jsonObject = new JSONObject(resultBean.getData());
                        String caselots = jsonObject.getString("caselots");
                        List<TogetherHallItem> netresultinfos = JSON.parseArray(caselots,
                                TogetherHallItem.class);
                        if (maxResult > netresultinfos.size()) {//当返回的子项数小于页数
                            togetherbuy_list.disableLoadmore();
                        }
                        if (isLoadMore) {
                            isLoadMore = false;
                            togetherbuyListAdapter.insert(netresultinfos);
                        } else {
                            this.togetherbuyInfos.clear();
                            for (int i = 0; i < netresultinfos.size(); i++) {
                                TogetherHallItem info = netresultinfos.get(i);
                                if (info.getSortState() == 1) {
                                    netresultinfos.remove(i);
                                    netresultinfos.add(0,info);
                                    break;
                                }
                            }
                            this.togetherbuyInfos.addAll(netresultinfos);
                            togetherbuyListAdapter.notifyDataSetChanged();
                        }
                        if (togetherbuyInfos.size() == 0) {
                            AppToast.getToast().show(R.string.text_norecord);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    if (isLoadMore) {
                        pageIndex--;
                    }
                    showToast(resultBean.getMsg());
                }
                break;
        }
    }

    @Override
    protected void onFailure(int requestCode, String erro, String message) {
        if (erro.equals("900003") && pageIndex == 1) {
            netProgressView.setVisibility(View.VISIBLE);
            netProgressView.noneRecord(message);
            togetherbuy_list.disableLoadmore();
        } else {
            togetherbuy_list.disableLoadmore();
            showToast("没有更多");
            togetherbuyListAdapter.getCustomLoadMoreView().setVisibility(View.GONE);
        }
        if (isLoadMore) {
            pageIndex--;
            isLoadMore = false;
        }
    }

    private void initView() {
        topView.setCenterText("合买");
        topView.setOnTitleClickListener(this);
        topView.setRight2Img(R.drawable.icon_togetherfilter);
        topView.setRight2Visible(View.VISIBLE);
        top_popup = new TogetherFilterPop(this,
                LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        top_popup.setOnFilterOKListener(this);
        togetherbuy_list.setHasFixedSize(false);
        final ScrollSmoothLineaerLayoutManager mgm = new ScrollSmoothLineaerLayoutManager(this,
                LinearLayoutManager.VERTICAL, false, 300);

        togetherbuy_list.setLayoutManager(mgm);
        togetherbuy_list.setDefaultOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pageIndex = 1;
                        net();
                        enableLoadMore();
                    }
                }, 1000);
            }
        });
        togetherbuyListAdapter = new TogetherbuyListAdapter(getContext(), togetherbuyInfos);
        enableEmptyViewPolicy();
        togetherbuyListAdapter.setOnItemClickListener(this);
        enableLoadMore();
        togetherbuy_list.setAdapter(togetherbuyListAdapter);
        togetherbuy_list.addItemDecoration(new RecyclerView.ItemDecoration() {


            //获取分割线尺寸
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView
                    .State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.set(0, 0, 0, 2);
            }


            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
                final int left = 0;
                final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
                final int childSize = parent.getChildCount();
                for (int i = 0; i < childSize; i++) {
                    final View child = parent.getChildAt(i);
                    RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child
                            .getLayoutParams();
                    final int top = child.getBottom() + layoutParams.bottomMargin;
                    final int bottom = top + 2;
                    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                    paint.setColor(getResources().getColor(R.color.color_cccccc));
                    paint.setStyle(Paint.Style.FILL);
                    c.drawRect(left, top, right, bottom, paint);
                }
            }
        });
        hm_rdg_filter.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.hm_filter_progress:
                        pageIndex = 1;
                        sortType = SORTTYPE_PROGRESS;
                        net();
                        break;
                    case R.id.hm_filter_amount:
                        pageIndex = 1;
                        sortType = SORTTYPE_MONEY;
                        net();
                        break;
                }
            }
        });

    }

    protected void enableEmptyViewPolicy() {
        togetherbuy_list.setEmptyView(R.layout.empty_view, UltimateRecyclerView
                .EMPTY_SHOW_LOADMORE_ONLY);
    }

    private void enableLoadMore() {
        togetherbuy_list.reenableLoadmore();
        togetherbuy_list.setLoadMoreView(R.layout.custom_bottom_progressbar);
        togetherbuy_list.setOnLoadMoreListener(new UltimateRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore(int itemsCount, final int maxLastVisiblePosition) {
                if (itemsCount >= pageIndex * maxResult) {
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            isLoadMore = true;
                            pageIndex++;
                            net();
                        }
                    }, 1000);
                }
            }
        });
    }


    @Override
    public void onRightClick() {
        Intent intent = new Intent(getContext(), InfoDetailActivity.class);
        intent.putExtra(IntentParamUtils.TITLE, getHelpTitle());
        intent.putExtra(IntentParamUtils.URL, getHelpUrl());
        startActivity(intent);
    }

    @Override
    public void onRight2Click() {
        // TODO Auto-generated method stub
        top_popup.showAsDropDown(topView);
    }

    public String getHelpUrl() {
        return HelpUrlConstants.Help_HM;
    }

    public String getHelpTitle() {
        return getString(R.string.help_hemai);
    }


    @Override
    public void onItemClick(TogetherHallItem data) {
        if (AppLotteryInfos.getcurrent_version_lotterys().contains(data.getLotteryType())) {
            Intent intent = new Intent(this, HeMaiGenDanActivity.class);
            intent.putExtra(IntentParamUtils.HM_HALLDETAIL_ID, data.getCaseId());
            startActivity(intent);
        } else {
            new AlertDialog.Builder(this).setMessage("本版本，不支持" + data.getLotteryTypeName() +
                    "的合买认购，请更新到最新版本").setPositiveButton("确定", new DialogInterface.OnClickListener
                    () {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }).create().show();
        }

    }

    @Override
    public void onFilterOK(String filterTage, int garantee, int isfill) {
        isSafeAmount = garantee;
        lotteryId = filterTage;
        state = isfill;
        net();
    }
}
